package software.hust.com.hust_last.util;

import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.StaggeredGridLayoutManager;


public abstract class RecyclerLoadListener extends RecyclerView.OnScrollListener {

    private int mLastVisibleItem;
    private int[] lastPositions;

    @Override
    public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
        super.onScrolled(recyclerView, dx, dy);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();

        if (layoutManager instanceof LinearLayoutManager) {
            LinearLayoutManager manager = (LinearLayoutManager) layoutManager;
            mLastVisibleItem = manager.findLastVisibleItemPosition();
        } else if (layoutManager instanceof GridLayoutManager) {
            GridLayoutManager manager = (GridLayoutManager) layoutManager;
            mLastVisibleItem = manager.findLastVisibleItemPosition();
        } else if (layoutManager instanceof StaggeredGridLayoutManager) {
            StaggeredGridLayoutManager manager = (StaggeredGridLayoutManager) layoutManager;
            if (lastPositions == null) {
                lastPositions = new int[manager.getSpanCount()];
            }
            manager.findLastVisibleItemPositions(lastPositions);
            mLastVisibleItem = findMax(lastPositions);
        }
    }

    private int findMax(int[] arr) {
        int max = arr[0];
        for (int i : arr) {
            if (i > max) {
                max = i;
            }
        }
        return max;
    }

    @Override
    public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
        super.onScrollStateChanged(recyclerView, newState);
        RecyclerView.LayoutManager layoutManager = recyclerView.getLayoutManager();
        int visibleCount = recyclerView.getChildCount();
        int totalCount = layoutManager.getItemCount();
        if (visibleCount > 0 && newState == RecyclerView.SCROLL_STATE_IDLE && mLastVisibleItem >= totalCount - 1) {
            onLoadMore();
        }
    }

    public abstract void onLoadMore();
}